package io.renren.modules.sys.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.renren.modules.oss.cloud.CloudStorageService;
import io.renren.modules.oss.cloud.OSSFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 云存储
 * @author Administrator
 *
 */
@Controller("/sys/cloudStorage")
public class CloudStorageController extends AbstractController {

   @RequestMapping(value = "/saveImg", method = RequestMethod.POST)
   @ResponseBody
   public JSONObject uploadImgToOSS(HttpServletRequest request, HttpServletResponse response) {  
       JSONObject jsonObject=new JSONObject();  
       try {  
           request.setCharacterEncoding("UTF-8");  
       } catch (UnsupportedEncodingException e) {  
           e.printStackTrace();  
       }  
       Part part = null;  
       try {  
           part = request.getPart("cloudFileName");// cloudFileName是文件域的name属性值  
       } catch (IOException e) {  
           e.printStackTrace();  
       } catch (ServletException e) {  
           e.printStackTrace();  
       }  
       // 包含原始文件名的字符串  
       String fi = part.getHeader("content-disposition");  
       // 提取文件拓展名  
       String fileNameExtension = fi.substring(fi.indexOf("."), fi.length() - 1);  
       // 生成实际存储的真实文件名  
       String realName = UUID.randomUUID().toString() + fileNameExtension;  
       String dir = "images/";
       String realPath = "";
       try {  
           InputStream inputStream = part.getInputStream();  
           CloudStorageService cloudStorageService = OSSFactory.build();
           realPath = cloudStorageService.upload(inputStream, dir+realName);
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       // 返回图片的URL地址  
       JSONArray jsonArray=new JSONArray();  
       jsonArray.add(realPath);  
       jsonObject.put("errno",0);  
       jsonObject.put("data",jsonArray);  
       return jsonObject;  
   }
}
